package com.zhike.api.handler;

import java.util.List;

import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.http.HttpStatus;

@RestControllerAdvice("com.zhike.api.controller")
public class GlobalParameterExceptionHandler {

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public String paramExceptionHandler(MethodArgumentNotValidException e){
        BindingResult result = e.getBindingResult();
        if(result.hasErrors()){
            List<ObjectError> allErrors = result.getAllErrors();
            if (allErrors.size()>0){
                ObjectError error = allErrors.get(0);
                return error.getDefaultMessage();
            }
        }
        return "请求参数错误";
    }
}
